<template>
  <div class="bgc-default">
    <div class="circle-2-tab pad-l-20 pad-r-20 pad-t-20">
      <!-- 基本信息 -->
      <el-form :model="contentForm" label-width="130px" ref="contentBaseForm" class="pad-t-1">
        <el-form-item label="基本信息" class="one-label">
          <el-form-item :label="contentForm.contentType == 1 ? '图文名称：' : '视频名称：'" 
            label-width="170px" prop="contentName" 
            :rules="requiredRule(contentForm.contentType == 1 ? '图文名称' : '视频名称')">
            <el-input v-model="contentForm.contentName" class="long-input" placeholder="最多输入40个字" maxlength="40" show-word-limit/>
          </el-form-item>
          <el-form-item label="作者：" label-width="170px" prop="sortNo">
            <div class="flex v-align-c">
              <img v-if="contentForm.contentAuthorId" :src="contentForm.avatar" class="user-avatar mar-r-10"/>
              <span v-if="contentForm.contentAuthorId" class="mar-r-30">{{ contentForm.nickname }}</span>
              <el-button type="text" @click="openMemberSelect">{{ this.contentForm.contentAuthorId ? '重新选择' : '添加作者' }}</el-button>
            </div>
          </el-form-item>
          <el-form-item 
            :label="contentForm.contentType == 1 ? '图文封面：' : '视频封面：'" 
            label-width="170px" prop="coverUrl"
            :rules="requiredRule(contentForm.contentType == 1 ? '图文封面' : '视频封面')">
            <div class="width-155">
              <el-upload list-type="picture-card" 
                action="/api/common/uploadFiles" 
                accept="image/jpeg, image/gif, image/png, image/bmp" 
                name="files" 
                :data="token" 
                :show-file-list="false"
                v-loading="fileLoading" 
                :on-success="handleUploadCoverSuccess" 
                :before-upload="beforeUpload">
                  <img v-if="contentForm.coverUrl" :src="contentForm.coverUrl" class="img-box"/>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <div class="font-12 font-color-9">建议尺寸750*420像素（16:9），小于3M，支持jpg、png、jpg格式。</div>
          </el-form-item>
          <el-form-item label="分享文案：" label-width="170px" prop="shareName" :rules="requiredRule('分享文案')">
            <el-input v-model="contentForm.shareName" class="long-input" placeholder="最多输入13个字" maxlength="13" show-word-limit/>
          </el-form-item>
          <el-form-item label="分享海报：" label-width="170px">
            <div class="width-155">
              <el-upload list-type="picture-card" 
                action="/api/common/uploadFiles" 
                accept="image/jpeg, image/gif, image/png, image/bmp" 
                name="files" 
                :data="token" 
                :show-file-list="false"
                v-loading="fileLoading" 
                :on-success="handleUploadPosterSuccess" 
                :before-upload="beforeUpload">
                  <img v-if="contentForm.sharePosterUrl" :src="contentForm.sharePosterUrl" class="img-box"/>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <div class="font-12 font-color-9">建议尺寸420*420像素（1:1），小于3M，支持jpg、png、jpg格式。</div>
          </el-form-item>
        </el-form-item>
      </el-form>

      <!-- 图文详情 -->
      <el-form :model="contentForm" label-width="130px" ref="contentPicForm" class="pad-t-1">
        <el-form-item :label="contentForm.contentType == 1 ? '图文详情' : '图文简介'" class="one-label">
          <el-form-item :label="contentForm.contentType == 1 ? '完整图文：' : '图文简介：'" 
            label-width="170px" 
            prop="content"
            :rules="contentForm.contentType == 1 ? requiredRule('图文详情') : []">
            <vue-ueditor-wrap ref="editor" style="width: 680px;line-height: 22px;" v-model="contentForm.content" :config="ueConfig"></vue-ueditor-wrap>
          </el-form-item>
        </el-form-item>
      </el-form>

      <!-- 视频详情 -->
      <el-form v-if="contentForm.contentType == 2" :model="contentForm" label-width="130px" ref="contentVideoForm" class="pad-t-1">
        <el-form-item label="视频详情" class="one-label">
          <el-form-item label="完整视频：" label-width="170px" prop="videoUrl" :rules="requiredRule('完整视频：')">
            <div style="width: 425px">
              <el-upload list-type="picture-card" 
                action="/api/common/uploadFiles" 
                accept="image/mp4"
                class="video-box"
                name="files" 
                :data="token" 
                :show-file-list="false"
                v-loading="fileLoading" 
                :on-success="handleUploadVideoSuccess" 
                :before-upload="beforeVideoUpload">
                  <video controls="controls" height="200px"
                    v-if="contentForm.videoUrl" :src="contentForm.videoUrl">
                    <source type="video/mp4">
                    Your browser does not support the video tag.
                  </video>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <div class="font-12 font-color-9">视频大小不超过50M，建议时长10~30分钟，宽高比16:9，仅支持mp4格式。</div>
          </el-form-item>
        </el-form-item>
      </el-form>
    </div>

    <div class="bottom-bar">
      <el-button plain @click="doBack">返回</el-button>
      <el-button type="primary" @click="doSave">保存</el-button>
    </div>
    
    <!--微客选择器-->
    <el-dialog title="微客选择器" :visible.sync="memberVisible" :close-on-press-escape="true" width="650px">
      <div class="scroll-layer-box">
        <member-select :showFlag="memberVisible" @selectEvent="selectEvent"></member-select>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'
  import { getContent, saveContent } from '@/api/content/contentInfo'
  import VueUeditorWrap from 'vue-ueditor-wrap'
  import memberSelect from './components/member-select'

  export default {
    components: { VueUeditorWrap, memberSelect },
    data() {
      return {
        // 内容表单
        contentForm: {
          // 云店应用类型
          appType: 10,
          enterpriseId: this.getEnterpriseId(),
          contentInfoId: '',
          contentName: '',
          contentType: '',
          contentAuthorId: '',
          nickname: '',
          avatar: '',
          coverUrl: '',
          shareName: '',
          sharePosterUrl: '',
          videoUrl: '',
          contentDetailId: '',
          content: ''
        },
        token: '',
        memberVisible: false,
        fileLoading: false,
        ueConfig: {
          toolbars: [['source', 'undo', 'fontsize', 'paragraph', '|', 'bold', 'italic', 'underline', 'strikethrough', 'forecolor', 'backcolor', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', 'blockquote', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'simpleupload', 'removeformat', 'inserttable', 'deletetable', 'insertrow', 'deletecol', 'insertcol', 'deleterow', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols']],
          // 初始容器高度
          initialFrameHeight: 300,
          // 初始容器宽度
          initialFrameWidth: '100%'
        }
      }
    },
    created() {
      this.token = { accessToken: getToken() }
      const queryParams = this.getCurrentPage().query
      if (queryParams.contentType) {
        this.contentForm.contentType = parseInt(queryParams.contentType)
      }
      if (queryParams.contentInfoId) {
        this.contentForm.contentInfoId = queryParams.contentInfoId
        this.init()
      }
    },
    methods: {
      // 初始化
      init() {
        getContent(this.contentForm.contentInfoId).then(response => {
          Object.assign(this.contentForm, response.data)
        })
      },
      // 必输校验
      requiredRule(labelName) {
        return [{ required: true, message: '请输入' + labelName, trigger: 'blur' }]
      },
      // 打开微客选择器事件
      openMemberSelect() {
        this.memberVisible = true
      },
      // 微客选择事件
      selectEvent(data) {
        this.contentForm.contentAuthorId = data.memberId
        this.contentForm.nickname = data.nickname
        this.contentForm.avatar = data.avatar
        this.memberVisible = false
      },
      // 文件上传前校验
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'
        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message({ type: 'error', message: '上传图片必须是JPG/GIF/PNG/BMP 格式!' })
        } else {
          this.fileLoading = true
        }
        return (isJPG || isBMP || isGIF || isPNG)
      },
      // 视频上传前校验
      beforeVideoUpload(file) {
        const isMP4 = file.type === 'video/mp4'
        if (!isMP4) {
          this.$message.error('上传视频必须是MP4 格式!')
        } else {
          this.fileLoading = true
        }
        return (isMP4)
      },
      // 封面上传成功后事件
      handleUploadCoverSuccess(res, file) {
        this.fileLoading = false
        if (res.code === 101) {
          this.contentForm.coverUrl = res.data[0]
        } else {
          this.$message({ type: 'error', message: res.msg })
        }
      },
      // 海报上传成功后事件
      handleUploadPosterSuccess(res, file) {
        this.fileLoading = false
        if (res.code === 101) {
          this.contentForm.sharePosterUrl = res.data[0]
        } else {
          this.$message({ type: 'error', message: res.msg })
        }
      },
      // 视频上传成功后事件
      handleUploadVideoSuccess(res, file) {
        this.fileLoading = false
        if (res.code === 101) {
          this.contentForm.videoUrl = res.data[0]
        } else {
          this.$message({ type: 'error', message: res.msg })
        }
      },
      // 返回事件
      doBack() {
        this.$router.go(-1)
      },
      // 保存事件
      doSave() {
        const baseForm = new Promise((resolve, reject) => {
          this.$refs['contentBaseForm'].validate((valid) => {
            if (valid) resolve()
          })
        })
        const picForm = new Promise((resolve, reject) => {
          this.$refs['contentPicForm'].validate((valid) => {
            if (valid) resolve()
          })
        })
        const videoForm = new Promise((resolve, reject) => {
          if (this.$refs['contentVideoForm']) {
            this.$refs['contentVideoForm'].validate((valid) => {
              if (valid) resolve()
            })
          } else {
            resolve()
          }
        })
        Promise.all([baseForm, picForm, videoForm]).then(() => {
          saveContent(this.contentForm).then(response => {
            if (response.isError) return
            this.$message({ message: '保存成功', type: 'success' })
            this.doBack()
          })
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .circle-2-tab {
    padding-bottom: 70px;
    /deep/ .el-form-item {
      background: white;
    }
    /deep/.one-label>.el-form-item__content {
      border-left:#F7F8FA 10px solid;
      .el-form-item__label {
        font-size: 14px;
      }
    }
    /deep/ .el-form-item__content {
      font-size: 14px;
    }
    /deep/ .el-radio__label {
      font-size: 14px;
    }
    /deep/ .el-radio__inner {
      width: 14px;
      height: 14px;
    }
  }
  .long-input {
    width: 60%;
  }
  .img-box {
    width: 150px;
    height: 150px;
  }
  .video-box {
    /deep/ .el-upload--picture-card {
      width: 425px;
      height: 200px;
      line-height: 206px;
    }
  }
  .bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 72px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: white;
    z-index: 999;
    box-shadow: 0 -2px 8px #eeeeee;
    .el-button {
      width: 100px;
      height: 40px;
      line-height: 40px;
      padding: 0;
    }
  }
  .user-avatar {
    width: 45px;
    height: 45px;
    display: block;
    border-radius: 50%;
  }
</style>